import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:ui' as ui;

import 'package:flutter/scheduler.dart';

/// 基于 LeafRenderObjectWidget 实现的自定义文字绘制组件
class CustomTextPainter extends LeafRenderObjectWidget {
  final String text;
  final double mScreenW;
  final TextStyle textStyle;
  final Duration animationDuration;
  final VoidCallback? onAnimationComplete;

  const CustomTextPainter({
    Key? key,
    required this.text,
    required this.mScreenW,
    this.textStyle = const TextStyle(
      fontSize: 24,
      color: Colors.black,
      fontWeight: FontWeight.normal,
    ),
    this.animationDuration = const Duration(seconds: 6),
    this.onAnimationComplete,
  }) : super(key: key);

  @override
  RenderObject createRenderObject(BuildContext context) {
    return RenderCustomText(
      text: text,
      screenWidth: mScreenW,
      textStyle: textStyle,
      animationDuration: animationDuration,
      onAnimationComplete: onAnimationComplete,
    );
  }

  @override
  void updateRenderObject(BuildContext context, RenderCustomText renderObject) {
    renderObject
      ..text = text
      ..screenWidth = mScreenW
      ..textStyle = textStyle
      ..animationDuration = animationDuration
      ..onAnimationComplete = onAnimationComplete;
  }
}

/// 负责实际渲染的 RenderObject 类
class RenderCustomText extends RenderBox implements TickerProvider {
  String _text;
  double _screenWidth;
  TextStyle _textStyle;
  Duration _animationDuration;
  VoidCallback? _onAnimationComplete;

  late AnimationController _controller;
  late Animation<Offset> _animation;
  Ticker? _ticker;

  RenderCustomText({
    required String text,
    required double screenWidth,
    required TextStyle textStyle,
    required Duration animationDuration,
    VoidCallback? onAnimationComplete,
  })  : _text = text,
        _screenWidth = screenWidth,
        _textStyle = textStyle,
        _animationDuration = animationDuration,
        _onAnimationComplete = onAnimationComplete {
    _initializeAnimation();
  }

  String get text => _text;
  set text(String value) {
    if (_text != value) {
      _text = value;
      markNeedsLayout();
      markNeedsPaint();
    }
  }

  double get screenWidth => _screenWidth;
  set screenWidth(double value) {
    if (_screenWidth != value) {
      _screenWidth = value;
      _updateAnimation();
      markNeedsLayout();
    }
  }

  TextStyle get textStyle => _textStyle;
  set textStyle(TextStyle value) {
    if (_textStyle != value) {
      _textStyle = value;
      markNeedsLayout();
      markNeedsPaint();
    }
  }

  Duration get animationDuration => _animationDuration;
  set animationDuration(Duration value) {
    if (_animationDuration != value) {
      _animationDuration = value;
      _controller.duration = value;
    }
  }

  VoidCallback? get onAnimationComplete => _onAnimationComplete;
  set onAnimationComplete(VoidCallback? value) {
    if (_onAnimationComplete != value) {
      _onAnimationComplete = value;
    }
  }

  @override
  Ticker createTicker(TickerCallback onTick) {
    _ticker ??= Ticker(onTick, debugLabel: 'RenderCustomText');
    return _ticker!;
  }

  void _initializeAnimation() {
    _controller = AnimationController(
      duration: _animationDuration,
      vsync: this,
    );

    _updateAnimation();

    _controller.forward().whenComplete(() {
      _onAnimationComplete?.call();
    });
  }

  void _updateAnimation() {
    final textWidth = _calculateTextWidth();
    _animation = Tween<Offset>(
      begin: Offset(_screenWidth, 0),
      end: Offset(-textWidth, 0.0),
    ).animate(CurvedAnimation(parent: _controller, curve: Curves.linear));
  }

  /// 计算文本实际显示宽度
  double _calculateTextWidth() {
    final textPainter = TextPainter(
      text: TextSpan(
        text: _text,
        style: _textStyle,
      ),
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(minWidth: 0, maxWidth: double.infinity);
    return textPainter.width;
  }

  @override
  void performLayout() {
    final textWidth = _calculateTextWidth();
    final textHeight = TextPainter(
      text: TextSpan(text: _text, style: _textStyle),
      textDirection: TextDirection.ltr,
    )..layout(minWidth: 0, maxWidth: double.infinity);

    size = Size(textWidth, textHeight.height);
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    print("偏移距离 ${offset}");
    final canvas = context.canvas;

    canvas.save();
    canvas.translate(offset.dx, offset.dy);

    // 应用动画偏移
    if (_animation.value != null) {
      canvas.translate(_animation.value.dx, _animation.value.dy);
    }

    // 创建文本画笔
    final textPainter = TextPainter(
      text: TextSpan(
        text: _text,
        style: _textStyle,
      ),
      textDirection: TextDirection.ltr,
    );

    // 布局并绘制文本
    textPainter.layout(minWidth: 0, maxWidth: double.infinity);
    textPainter.paint(canvas, Offset.zero);

    canvas.restore();
  }

  @override
  void dispose() {
    _controller.dispose();
    _ticker?.dispose();
    super.dispose();
  }
}
